package com.commerce.recording.activity;


import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Dialog;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.ServiceConnection;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.IBinder;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.view.animation.LinearInterpolator;
import android.view.inputmethod.InputMethodManager;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.appcompat.app.AppCompatActivity;
import androidx.core.app.ActivityCompat;

import com.commerce.recording.R;
import com.commerce.recording.adapter.MylistAdapter;
import com.commerce.recording.entity.Record;
import com.commerce.recording.entity.Sign;
import com.commerce.recording.service.RecordService;
import com.commerce.recording.utils.Delete;
import com.commerce.recording.utils.FormatDate;

import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

public class MainActivity extends AppCompatActivity implements View.OnClickListener {

    private TextView textTime;
    private ImageView btnRecord;
    private ImageView btnComplete;
    private ImageView btnList;
    private ImageView btnSign;
    private ImageView btnRun1;
    private ImageView btnRun2;
    private ListView listView;
    private TextView textToast;
    private Boolean b = true;
    private Intent intent;
    RecordService.DownloadBinder downloadBinder;
    private Animation animationStop;
    private Animation animationStart;
    private Animation animationrun2;
    private Animation animationrun1;
    private Animation animationrun;
    private long timeMillis;
    private Timer timer;
    private List<Sign> list = new ArrayList<>();

    //监视应用程序服务状态的接口
    ServiceConnection serviceConnection = new ServiceConnection() {
        @Override
        public void onServiceConnected(ComponentName name, IBinder service) {
            downloadBinder = (RecordService.DownloadBinder) service;
        }

        @Override
        public void onServiceDisconnected(ComponentName name) {
        }
    };
    private MylistAdapter mylistAdapter;
    private Animation animationUp;
    private int timectl;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ActivityCompat.requestPermissions(MainActivity.this,new String[]{
                Manifest.permission.READ_EXTERNAL_STORAGE,
                Manifest.permission.WRITE_EXTERNAL_STORAGE,
                Manifest.permission.RECORD_AUDIO
        },201);
        initView();
    }

    private void initView() {
        findViewById(R.id.main_tv_setting).setOnClickListener((v -> startActivity(new Intent(MainActivity.this, SettingActivity.class))));
        btnRecord = findViewById(R.id.main_img_record);
        btnComplete = findViewById(R.id.main_img_complete);
        btnSign = findViewById(R.id.main_img_sign);
        btnList = findViewById(R.id.main_img_list);
        btnRun1 = findViewById(R.id.main_img_run1);
        btnRun2 = findViewById(R.id.main_img_run2);
        textTime = findViewById(R.id.main_tv_time);
        listView = findViewById(R.id.main_list_signs);
        textToast = findViewById(R.id.main_tv_toast);
        //加载动画
        animationrun = AnimationUtils.loadAnimation(this, R.anim.run);
        animationrun1 = AnimationUtils.loadAnimation(this, R.anim.run1);
        animationrun2 = AnimationUtils.loadAnimation(this, R.anim.run2);
        animationStart = AnimationUtils.loadAnimation(this, R.anim.start);
        animationStop = AnimationUtils.loadAnimation(this, R.anim.stop);
        animationUp = AnimationUtils.loadAnimation(this, R.anim.up);
        animationUp.setFillAfter(true);
        //运行速度
        LinearInterpolator li = new LinearInterpolator();
        animationStart.setInterpolator(li);
        animationStop.setInterpolator(li);
        animationrun1.setInterpolator(li);
        animationrun2.setInterpolator(li);

        btnRecord.setImageResource(R.drawable.start);
        btnSign.setImageResource(R.drawable.signon);

        btnSign.setEnabled(false);
        btnSign.setOnClickListener(this);
        btnComplete.setOnClickListener(this);
        btnRecord.setOnClickListener(this);
        btnList.setOnClickListener(this);
    }

    //弹窗动画
    private void animation(String toast) {
        new Thread(() -> {
            try {
                runOnUiThread(() -> {
                    textToast.setVisibility(View.VISIBLE);
                    textToast.setText(toast);
                });
                Thread.sleep(500);
                runOnUiThread(() -> {
                    textToast.setAnimation(animationUp);
                    textToast.startAnimation(animationUp);
                });
                Thread.sleep(2000);
                runOnUiThread(() -> textToast.setVisibility(View.GONE));
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

        }).start();
    }

    @SuppressLint("NonConstantResourceId")
    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.main_img_complete:
                stop();
                break;
            case R.id.main_img_record:
                replace();
                break;
            case R.id.main_img_sign:
                animation("已标记");
                list = downloadBinder.sginRecording();
                if (mylistAdapter == null) {
                    mylistAdapter = new MylistAdapter(this, list);
                    listView.setAdapter(mylistAdapter);
                } else {
                    mylistAdapter.notifyDataSetChanged();
                }
                break;
            case R.id.main_img_list:
                startActivity(new Intent(MainActivity.this, SeeActivity.class));
                break;
        }
    }

    private void replace() {
        if (b) {
            b = false;
            //设置动画
            btnRecord.setAnimation(animationStop);
            btnRecord.startAnimation(animationStop);
            btnRun2.setAnimation(animationrun2);
            btnRun1.setAnimation(animationrun1);
            btnRecord.setImageResource(R.drawable.stop);
            //开启
            if (intent == null) {
                intent = new Intent(this, RecordService.class);
                animation("开始录音");
                //启动服务
                startService(intent);
                btnSign.setEnabled(true);
                //绑定服务
                bindService(intent, serviceConnection, BIND_AUTO_CREATE);
                timeMillis = System.currentTimeMillis();
                timer = new Timer();
                //旋转图片
                timer.schedule(new MyTask(), 0, 100);
                btnComplete.setVisibility(View.VISIBLE);
                //设置动画
                btnComplete.setAnimation(animationrun);
                //启动动画
                btnComplete.startAnimation(animationrun);
                btnList.setVisibility(View.GONE);
            } else if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N && downloadBinder != null) {
                animation("继续录音");
                downloadBinder.startRecording();
                btnSign.setEnabled(true);
                timer = new Timer();
                timer.schedule(new MyTask(), 0, 100);
            } else {
                animation("设备不支持");
                stop();
            }
        } else {
            b = true;
            btnRecord.setAnimation(animationStart);
            btnRecord.startAnimation(animationStart);
            btnRun2.clearAnimation();
            btnRun1.clearAnimation();
            btnRecord.setImageResource(R.drawable.start);

            if (downloadBinder != null && Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                animation("停止录音");
                btnSign.setEnabled(false);
                downloadBinder.stopRecording();
                timer.cancel();
                timer.purge();
            } else {
                stop();
            }
        }
    }


    private class MyTask extends TimerTask {
        @Override
        public void run() {
            timectl += 100;
            String times = FormatDate.toHHmmssS(timectl);
            runOnUiThread(() -> textTime.setText(times));
        }
    }

    /**
     * 停止方法
     */
    private void stop() {
        btnSign.setEnabled(false);
        timer.cancel();
        timer.purge();
        textTime.setText("");
        if (!b) {
            replace();
        }
        ;
        if (downloadBinder != null) {
            Record record = downloadBinder.nullRecording();
            if (getSharedPreferences("sp_name_audio", MODE_PRIVATE).getBoolean("Dialog", false)) {
                show(record);
            } else {
                record.save();
                animation("录音已保存");
            }
            timectl = 0;
            unbindService(serviceConnection);
            stopService(intent);
            downloadBinder = null;
            intent = null;
            mylistAdapter = null;
        }
        btnComplete.setVisibility(View.GONE);
        btnList.setVisibility(View.VISIBLE);
        btnList.setAnimation(animationrun);
        btnList.startAnimation(animationrun);
    }

    private void show(Record record) {
        Dialog builder = new Dialog(MainActivity.this,R.style.BottomDialog);
        View view = LayoutInflater.from(MainActivity.this).inflate(R.layout.rename_dialog, null);
        builder.setContentView(view);
        EditText renameTvName = view.findViewById(R.id.rename_tv_name);
        renameTvName.setText(record.getName());
        Button renameTvCanxcel = view.findViewById(R.id.rename_tv_cancel);
        Button renameTvConfirm = view.findViewById(R.id.rename_tv_confirm);
        ViewGroup.LayoutParams layoutParams = view.getLayoutParams();
        layoutParams.width = getResources().getDisplayMetrics().widthPixels;
        view.setLayoutParams(layoutParams);
        builder.setTitle("重命名");
        builder.setCancelable(false);
        builder.getWindow().setGravity(Gravity.BOTTOM);
        renameTvCanxcel.setOnClickListener((v -> {
            builder.cancel();
            String path = record.getPath();
            if(Delete.delete(path)){
             animation("已删除");
            }
        }));
        renameTvConfirm.setOnClickListener((v -> {
            builder.cancel();
            record.setName(renameTvName.getText().toString());
            record.save();
            animation("录音已保存");
        }));
        builder.show();
        openKeyboard(renameTvName);
    }
    /**
     * 打开键盘
     *
     * @param editText 操作的输入框
     */
    public static void openKeyboard(final EditText editText) {
        //设置可获得焦点
        editText.setFocusable(true);
        editText.setFocusableInTouchMode(true);
        //请求获得焦点
        editText.requestFocus();
        //调用系统输入法
        Timer timer = new Timer();
        timer.schedule(new TimerTask() {
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) editText
                        .getContext().getSystemService(
                                Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(editText, 0);
            }
        }, 300);
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        int n = grantResults.length;
        if (n < 1)
            return ;
        for (int i = 0; i < n; i++){
            if (PackageManager.PERMISSION_GRANTED != grantResults[i]){ //用户未授予权限定义中对应的权限
                //未授权，不能执行需要权限的操作。
                finish();
            }else{
                //已授权可以执行相应操作
            }
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }
}